package thread;


import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.BiConsumer;
import java.util.function.Function;

/**
 * \* User: Administrator
 * \* Date: 2020/11/19
 * \* Time: 9:50
 * \* Description:
 *
 */
public class CompletableFutureDemo {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        //无返回结果的异步任务
        CompletableFuture<Void> runAsync_runnable = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("runAsync runnable");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        //有返回结果的异步任务
        CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int a = 12/0;
            return "有结果异步任务";
        });


        //future whenComplete
        stringCompletableFuture.whenComplete((s1, throwable) -> {
            System.out.println(s1.concat("====whenComplete===执行完成"));
        });

        //future exceptionally
        stringCompletableFuture.exceptionally(throwable -> {
            System.out.println("future.exceptionally" + throwable.getMessage());
            return "异常exceptionally";
        });

        String s = stringCompletableFuture.get();
        System.out.println("supplyAsync结果：" + s);

        System.out.println("main end");
    }
}
